package com.net.jef.webx.fen.tool.module.screen;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.alibaba.citrus.turbine.Context;
import com.alibaba.citrus.turbine.Navigator;
import com.alibaba.citrus.turbine.dataresolver.Param;
import com.net.jef.util.HttpClientHelper;

public class ZipCodeService {

    private String zipCodeServiceUrl="http://www.webxml.com.cn/WebServices/ChinaZipSearchWebService.asmx/getAddressByZipCode";
//    http://www.webxml.com.cn/WebServices/ChinaZipSearchWebService.asmx/getAddressByZipCode?theZipCode=220000&userID=
    /**
     * @param args
     */
    public void execute(@Param("code") String code, Context context,
            Navigator nav,HttpServletRequest request) throws Exception {
        
        if(code==null) {
           return;
        }else{
            code=code.trim();
        }
        Map<String,String> params = new HashMap<String,String>();
        params.put("theZipCode", code);
        params.put("userID", "");

       String zipCodeString = HttpClientHelper.getResponseBodyAsString(zipCodeServiceUrl, params, 15, HttpClientHelper.POST_CONTENTTYPE_UTF8);
     
        String name="";
        
        Document xmlDoc = DocumentHelper.parseText(zipCodeString);  
        List<Element> list1= xmlDoc.selectNodes("//PROVINCE");
        List<Element> list2= xmlDoc.selectNodes("//CITY");
        List<Element> list3= xmlDoc.selectNodes("//ADDRESS");
        if(list1.size()>0){
            name =list1.get(0).getText() + (list2.size()>0? " "+list2.get(0).getText():"") + (list3.size()>0? " "+list3.get(0).getText():"");
        }
        
        context.put("code",code);
        context.put("name",name);
    }

}
